package com.xiaobaibai.units;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.xiaobaibai.bo.SubscribeMessageBo;
import com.xiaobaibai.common.WeixinCommon;
import com.xiaobaibai.entity.Order;
import com.xiaobaibai.entity.User;
import com.xiaobaibai.service.IOrderService;
import com.xiaobaibai.service.IUserService;
import com.xiaobaibai.threadPool.MyThreadPoolUnit;
import com.xiaobaibai.units.pay.HttpClientUnit;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.time.DateFormatUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.ApplicationArguments;
import org.springframework.boot.ApplicationRunner;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.CompletableFuture;

@Component
@Slf4j
public class OrderWXNewsUnit implements ApplicationRunner {

    /**
     * 订单消息通知
     */
    @Autowired
    private IUserService userService;

    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    @Autowired
    private IOrderService orderService;

    private final String sendNewsUrl="https://api.weixin.qq.com/cgi-bin/message/subscribe/send?access_token=%s";

    public static String token=null;//接口调用凭证

    private String url="";

    //订单取消结果通知(有允许,用拒绝)
    private final String cancelOrderNewId="ndwoVdHjikFqgnsdwDf3eMHCjr-MHsR6-PNqm9HMrQA";

    //拒绝退款通知
    private final String noRetrunNewId="rl-bcytcDlLt2Pu8C24s0wPnQQC0rcrDb6poCy5XFXQ";

    //同意退款通知
    private final String ageerReturnNewId="gr9Kl0kms8DlI6j6XRO8BEZnrkpQ-8tPnV2xZu53h-E";

    //取消订单结果(成功/失败)
    public void sendCancelResult(String phone,String orderId,boolean flag,String marks){
        CompletableFuture.runAsync(()->{
            String userOpenid = getOpenidByOrderId(orderId);
            Map<String,String> map=new HashMap<>();
            map.put("phrase3",flag?"已取消":"未取消");
            map.put("thing4",flag?"期待下次为您服务":marks);
            SubscribeMessageBo subscribeMessageBo=
                    new SubscribeMessageBo(token,userOpenid, cancelOrderNewId,map);
            JSONObject jsonObject = HttpClientUnit.messagePost(url, subscribeMessageBo);
            if(jsonObject.getInteger("errcode")!=0){
                SmsUnit.sendCancelResult(phone,orderId,flag?"已取消":"未取消",flag?"期待下次为您服务":marks);
            }
        }, MyThreadPoolUnit.threadPoolExecutor);
    }

    //拒绝退款通知
    public void sendNoReturn(String phone,String orderId,String marks){
        CompletableFuture.runAsync(()->{
            String userOpenid = getOpenidByOrderId(orderId);
            Map<String,String> map=new HashMap<>();
            map.put("character_string4",orderId);
            map.put("thing5",marks);
            SubscribeMessageBo subscribeMessageBo=
                    new SubscribeMessageBo(token,userOpenid,noRetrunNewId,map);
            JSONObject jsonObject = HttpClientUnit.messagePost(url, subscribeMessageBo);
            if(jsonObject.getInteger("errcode")!=0){
                SmsUnit.sendNoReturn(phone,orderId,marks);
            }

        }, MyThreadPoolUnit.threadPoolExecutor);
    }

    //同意退款通知
    public void sendAgreeReturn(String phone,String orderId,Double amount){
        CompletableFuture.runAsync(()->{
            String userOpenid = getOpenidByOrderId(orderId);
            Map<String,String> map=new HashMap<>();
            map.put("character_string4",orderId);
            map.put("amount3","￥"+amount.toString()+"元");
            map.put("thing5","期待下次为您服务");
            SubscribeMessageBo subscribeMessageBo=
                    new SubscribeMessageBo(token,userOpenid,ageerReturnNewId,map);
            JSONObject jsonObject = HttpClientUnit.messagePost(url, subscribeMessageBo);
            if(jsonObject.getInteger("errcode")!=0){
                SmsUnit.sendAgreeReturn(phone,orderId,amount.toString()+"元","期待下次为您服务");
            }

        }, MyThreadPoolUnit.threadPoolExecutor);
    }

    private String getOpenidByOrderId(String orderId){
        QueryWrapper<Order> q1=new QueryWrapper<>();
        q1.select("user_id");
        q1.eq("order_id",orderId);
        Order order = orderService.getOne(q1);
        QueryWrapper<User> q2=new QueryWrapper<>();
        q2.select("user_openid");
        q2.eq("user_id",order.getUserId());
        User user = userService.getOne(q2);
        return user.getUserOpenid();
    }

    @Override
    public void run(ApplicationArguments args) {
        String redisWxToken = stringRedisTemplate.opsForValue().get(WeixinCommon.WxAccessToken);
        if(redisWxToken==null) {
            log.error("请先启动客户端获取订阅消息token");
            throw new RuntimeException("启动错误");
        }
        token=redisWxToken;
        this.url=String.format(sendNewsUrl,token);
    }

}
